<template>
    <div class="sliderNumber" @dblclick="DblclickEvent">
        <div class="slider">
            <span v-if="!ShowInput" class="sliderBar">{{ value }}</span>
            <input v-if="ShowInput" v-model.number="value" ref="inputView" @keyup.enter="ShowInput = false"
                @blur="ShowInput = false" @input="adjustWidth" class="inputView" type="text" />
        </div>
        <div class="unitBox">
            <span>px</span>
            <CaretDownOutlined class="icon" />
        </div>
    </div>
</template>
<script setup>
import { CaretDownOutlined } from '@ant-design/icons-vue';
import { nextTick, ref, watch } from 'vue';
const inputView = ref();
const value = ref(120);

const ShowInput = ref(false);
const DblclickEvent = function () {
    ShowInput.value = true;
    nextTick(() => {
        inputView.value.focus();
    })
}
watch(ShowInput, val => {
    if (val) {
        nextTick(() => {
            adjustWidth();
        })
    }
})

let ElementCache = '';

function MouseDown() {
    ElementCache = document.createElement('div');
    ElementCache.style.position = 'fixed';
    ElementCache.style.width = '100%';
    ElementCache.style.height = '100%';
    ElementCache.style.top = 0;
    ElementCache.style.left = 0;
    ElementCache.style.cursor = 'e-resize';
    ElementCache.style.zIndex = '9999';
    ElementCache.style.background = '#ff0000';
    document.body.append(ElementCache);
}

function adjustWidth() {
    if (!inputView.value) return;
    var textWidth = getTextWidth(value.value);
    if (textWidth < 30) {
        textWidth = 30
    } else if (textWidth > 150) {
        textWidth = 150
    }
    inputView.value.style.width = textWidth + 10 + "px";
}

function getTextWidth(text) {
    var tempElement = document.createElement("div");
    tempElement.style.visibility = "hidden";
    tempElement.style.whiteSpace = "pre";
    tempElement.style.fontSize = "14px";
    tempElement.style.display = "inline-block";
    tempElement.textContent = text;
    document.body.appendChild(tempElement);
    var width = tempElement.offsetWidth;
    document.body.removeChild(tempElement);
    return width;
}


</script>
<style lang="less" scoped>
.sliderBar {
    cursor: e-resize;
    // position: fixed;
}

.inputView {
    display: inline-block;
    width: auto;
}

.icon {
    font-size: 12px;
}

.unitBox {
    display: flex;
    justify-content: center;
    align-items: center;
}

.slider {
    margin-right: 4px;
}

.sliderNumber {
    display: flex;
    width: 100%;
    height: 100%;
    justify-content: center;
    align-items: center;
}
</style>